package cn._2dland.uploader.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethodBase;

public class HttpUtils {
	/**
	 * 读取http请求的响应流，并以字符串形式返回
	 * @param method
	 * @return
	 */
	public static String readResponseStream(HttpMethodBase method) {
		String result = null;
		try {
			// 获取输入流
			InputStream is = method.getResponseBodyAsStream();
			// 获取相关参数 
			String charset = method.getResponseCharSet();
			// 处理gzip压缩
			Header header = method.getRequestHeader("Content-Encoding");
			if(header!=null && header.getValue().indexOf("gzip")>=0)
				is = new GZIPInputStream(is);

			// 构造输出流
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			for(int b; (b=is.read())>=0; ) {
				baos.write(b);
			}
			baos.flush();
			// 构造字符串
			result = charset==null ? 
					new String(baos.toByteArray()) : new String(baos.toByteArray(), charset);

			// 释放资源
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/*public static String escape(String str) {
		try {
			str = URLEncoder.encode("")
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}*/
}